package com.rainbow.bam.handler;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.rainbow.bam.properties.ServiceProperties;

/**
 * 全局异常处理类
 * 
 * @author HarrisonHan
 * @version $Id: GlobalErrorHandler.java, v 0.1 2015年11月10日 上午9:58:48 HarrisonHan Exp $
 */
@ControllerAdvice
public class GlobalErrorHandler {

    public static final String  DEFAULT_ERROR_VIEW = "error";
    /**
     * 日志
     */
    private static final Logger LOG                = LoggerFactory
                                                       .getLogger(GlobalErrorHandler.class);

    @Autowired
    private ServiceProperties   serviceProperties;
    
    /**
     * 默认系统异常拦截
     * 
     * @param exception
     * @param modelMap
     */
    @ExceptionHandler(Exception.class)
    public ModelAndView exception(Exception exception, HttpServletRequest httpServletRequest) {
        ModelAndView mav = new ModelAndView(DEFAULT_ERROR_VIEW);
        LOG.error("=====================systematic occurrence of errors====================");
        exception.printStackTrace();
        mav.addObject("message", exceptionMesssage(exception));
        mav.addObject("url", httpServletRequest.getHeader("Referer"));
        httpServletRequest.setAttribute("cdn", serviceProperties.getCdn());
        httpServletRequest.setAttribute("domain", serviceProperties.getDomain());
        if(exception instanceof AuthorizationException){
            mav.addObject("dologin",true);
        }else{
            mav.addObject("dologin",false);
        }
        return mav;
    }

    /**
     * 异常信息
     * 
     * @param e 异常
     * @return
     */
    private String exceptionMesssage(Exception e) {
        StringBuffer errorMsg = new StringBuffer();
        errorMsg.append("发生错误:");
        if (e instanceof NullPointerException) {
            errorMsg.append("空指针异常");
        } else if  (e instanceof AuthorizationException) {
            errorMsg.append("您未登录/没有相关操作权限.");
        }else {
            errorMsg.append(e.getMessage());
        }
        errorMsg.append("!!!");
        return errorMsg.toString();
    }

}
